package com.yhq.spring.web.util;

import com.alibaba.fastjson.JSONObject;
//import io.netty.handler.codec.base64.Base64Encoder;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.util.Asserts;
import org.apache.hc.core5.util.Timeout;
//import org.apache.http.HttpEntity;
//import org.apache.http.NameValuePair;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.client.entity.UrlEncodedFormEntity;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.message.BasicNameValuePair;
//import org.apache.http.util.Asserts;
//import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @description: 西墨设备第三方接口请求工具类
 * @author: 朱俊亮
 * @time: 2021-06-25 13:45
 */
public class XiMoUtil {

    private static final String URL = "https://api-cloud.thinmoo.com";

    /**
     * Redis中存放token的key
     */
    public static final String TOKEN = "XIMO_TOKEN";
    public static final Integer TOKEN_EXPIRE = 100;//西墨token默认120分钟失效，这里设置为100分钟
    public static final TimeUnit TOKEN_TIME_UNIT = TimeUnit.MINUTES;

    public static final String PWD_KEY_XIMO = "PWD_KEY_XIMO:";//西墨临时密码存放

    public static String getToken(String appId, String appSecret) {
        Map<String, String> urlParams = new LinkedHashMap<>();
        urlParams.put("appId", appId);
        urlParams.put("appSecret", appSecret);
        JSONObject result = GET("/platCompany/extapi/getAccessToken", urlParams);
        if (result.getInteger("code") == 0) {
            JSONObject data = result.getJSONObject("data");
            return data.getString("accessToken");
        }
        return null;
    }

    /**
     * GET方式请求西墨接口
     *
     * @param uri       传入接口路径
     * @param urlParams 传入查询条件
     * @return 返回操作信息
     * 状态码： -1：请求过程中异常(无法调通接口)
     * 0：西墨返回状态码（成功）
     * 1：西墨返回状态码（不成功）
     */
    public static JSONObject GET(String uri, Map<String, String> urlParams) {
        Asserts.notBlank(uri, "URI不能为空");
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            StringBuilder sb = new StringBuilder();
            if (urlParams != null) {
                sb.append("?");
                for (Map.Entry entry : urlParams.entrySet()) {
                    sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            HttpGet httpGet = new HttpGet(URL + uri + sb.toString());
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(Timeout.of(10000000,TimeUnit.MICROSECONDS)).build();
            //.setSocketTimeout(10000000).setConnectTimeout(10000000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("Accept", "application/json");
            httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String resultStr = EntityUtils.toString(entity, "utf-8");
            return JSONObject.parseObject(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();
        result.put("code", -1);
        result.put("message", "第三方接口请求失败");
        return result;
    }

    /**
     * POST方式请求西墨接口
     *
     * @param uri    传入接口路径
     * @param params 传入查询条件
     * @return 返回操作信息
     * 状态码： -1：请求过程中异常(无法调通接口)
     * 0：西墨返回状态码（成功）
     * 1：西墨返回状态码（不成功）
     */
    public static JSONObject POST(String uri, JSONObject params) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(URL + uri);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(Timeout.of(10000000,TimeUnit.MICROSECONDS)).build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            List<NameValuePair> paramList = new LinkedList<>();
            if (params != null && params.size() > 0) {
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(paramList, Charset.forName("utf-8")));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String resultStr = EntityUtils.toString(entity, Charset.forName("utf-8"));
            return JSONObject.parseObject(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();
        result.put("code", -1);
        result.put("message", "第三方接口请求失败");
        return result;
    }


    public static int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    public static char[] chars = {'A', 'B', 'C', 'D'};

    /**
     * 随机生成12位的字符串，生成规则：0~9,A,B,C,D 随机组合
     *
     * @return 返回12位随机字符串
     */
    public static String getCardMifareSecretKey() {
        StringBuilder sb = new StringBuilder("");
        Random random = new Random();
        while (true) {
            Integer index = random.nextInt(2);
            if (index == 0) {
                index = random.nextInt(numbers.length);
                sb.append(numbers[index]);
            } else if (index == 1) {
                index = random.nextInt(chars.length);
                sb.append(chars[index]);
            }
            if (sb.length() == 12) {
                break;
            }
        }
        return sb.toString();
    }

    /**
     * 本地文件（图片、excel等）转换成Base64字符串
     *
     * @param imgPath
     */
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小（字节）=" + in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        String base64Str =  Base64.getEncoder().encodeToString(data);;
        return base64Str;
    }

    /**
     * 网络图片转换Base64的方法
     *
     * @param netImagePath
     */
    public static String netImageToBase64(String netImagePath) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return  Base64.getEncoder().encodeToString(data.toByteArray());
    }

    public static void main(String[] args) throws Exception {
        String token = getToken("52d29ed54a3c4c61a1ccad57cd437aad", "41cc845f52a260ac4c5251dcfc538d1f");
        System.out.println(token);
//
//        JSONObject person = new JSONObject();
//        person.put("accessToken",token);
//        person.put("extCommunityId",37896);
//        person.put("id",100);
//
//        JSONObject jsonObject = XiMoUtil.POST("/wyEmpProperty/extapi/get",person);
//        System.out.println(jsonObject);
//        jsonObject = XiMoUtil.POST("/persEmpHousehold/extapi/get",person);
//        System.out.println(jsonObject);
//        String token = "239390079211a9c2967767aef60a4b43df9072f49ae3070ea9feee28c667acfa0f01e78777025a5dfd2f73e48bb07eca-p34532";
//        JSONObject person = new JSONObject();
//        person.put("accessToken",token);
//        person.put("extCommunityId",39812);
//        person.put("extCommunityUuid","c4ddc17ec9ec458ba0e4889ea9e60560");
//        String uuid = UUID.randomUUID().toString().replaceAll("-","");
//        person.put("uuid",uuid);
//        person.put("name","张三");
//        person.put("cardNos","1126084880");
//        person.put("isVerifyCardExists",0);
//        person.put("roomIds",5369624);
//        person.put("roomUuids","0e92dd66c7654752a26223a1ab1fa62b");
//        person.put("gender",2);
//        JSONObject jsonObject = XiMoUtil.POST("/wyEmpProperty/extapi/add",person);
//        System.out.println("传参："+person.toJSONString());
//        System.out.println("结果："+jsonObject.toJSONString());
//        System.out.println(NetImageToBase64("https://facegrup.oss-cn-hangzhou.aliyuncs.com/image/2022/01/10/8201641801783740.jpg"));
//        System.out.println(getUrlImageToBase64("https://facegrup.oss-cn-hangzhou.aliyuncs.com/image/2022/01/10/8201641801783740.jpg"));
    }

}
